<?php

namespace Admin\Controller;
use Admin\Model\AuthGroupModel;
use Think\Page;

/**文章控制器
 * Class ArticleController
 * @package Admin\Controller
 */
class ArticleController extends AdminController {

	/* 保存允许访问的公共方法 */
	static protected $allow = array( 'draftbox','mydocument');

    private $cate_id        =   null; //文档分类id

    /**
     * 检测需要动态判断的文档类目有关的权限
     *
     * @return boolean|null
     *      返回true则表示当前访问有权限
     *      返回false则表示当前访问无权限
     *      返回null，则会进入checkRule根据节点授权判断权限
     *
     * @author 朱亚杰  <xcoolcc@gmail.com>
     */
    protected function checkDynamic(){
        if(IS_ROOT){
            return true;//管理员允许访问任何页面
        }
        $cates = AuthGroupModel::getAuthCategories(UID);
        switch(strtolower(ACTION_NAME)){
            case 'index':   //文档列表
                $cate_id =  I('cate_id');
                break;
            case 'edit':    //编辑
            case 'update':  //更新
                $doc_id  =  I('id');
                $cate_id =  M('Document')->where(array('id'=>$doc_id))->getField('category_id');
                break;
            case 'setstatus': //更改状态
            case 'permit':    //回收站
                $doc_id  =  (array)I('ids');
                $cate_id =  M('Document')->where(array('id'=>array('in',$doc_id)))->getField('category_id',true);
                $cate_id =  array_unique($cate_id);
                break;
        }
        if(!$cate_id){
            return null;//不明,需checkRule
        }elseif( !is_array($cate_id) && in_array($cate_id,$cates) ) {
            return true;//有权限
        }elseif( is_array($cate_id) && $cate_id==array_intersect($cate_id,$cates) ){
            return true;//有权限
        }else{
            return false;//无权限
        }
        return null;//不明,需checkRule
    }

    /**
     * 显示左边菜单，进行权限控制
     * @author huajie <banhuajie@163.com>
     */
    protected function getMenu(){
        //获取动态分类
        $cate_auth  =   AuthGroupModel::getAuthCategories(UID);	//获取当前用户所有的内容权限节点
        $cate_auth  =   $cate_auth == null ? array() : $cate_auth;
        $cate       =   M('Category')->where(array('status'=>1))->field('id,title,pid,allow_publish')->order('pid,sort')->select();

        //没有权限的分类则不显示
        if(!IS_ROOT){
            foreach ($cate as $key=>$value){
                if(!in_array($value['id'], $cate_auth)){
                    unset($cate[$key]);
                }
            }
        }

        $cate           =   list_to_tree($cate);	//生成分类树

        //获取分类id
        $cate_id        =   I('param.cate_id');
        $this->cate_id  =   $cate_id;

        //是否展开分类
        $hide_cate = false;
        if(ACTION_NAME != 'recycle' && ACTION_NAME != 'draftbox' && ACTION_NAME != 'mydocument'){
            $hide_cate  =   true;
        }

        //生成每个分类的url
        foreach ($cate as $key=>&$value){
            $value['url']   =   'Article/index?cate_id='.$value['id'];
            if($cate_id == $value['id'] && $hide_cate){
                $value['current'] = true;
            }else{
                $value['current'] = false;
            }
            if(!empty($value['_child'])){
                $is_child = false;
                foreach ($value['_child'] as $ka=>&$va){
                    $va['url']      =   'Article/index?cate_id='.$va['id'];
                    if(!empty($va['_child'])){
                        foreach ($va['_child'] as $k=>&$v){
                            $v['url']   =   'Article/index?cate_id='.$v['id'];
                            $v['pid']   =   $va['id'];
                            $is_child = $v['id'] == $cate_id ? true : false;
                        }
                    }
                    //展开子分类的父分类
                    if($va['id'] == $cate_id || $is_child){
                        $is_child = false;
                        if($hide_cate){
                            $value['current']   =   true;
                            $va['current']      =   true;
                        }else{
                            $value['current'] 	= 	false;
                            $va['current']      =   false;
                        }
                    }else{
                        $va['current']      =   false;
                    }
                }
            }
        }
        $this->assign('nodes',      $cate);
        $this->assign('cate_id',    $this->cate_id);

        //获取面包屑信息
        $nav = get_parent_category($cate_id);
        $this->assign('rightNav',   $nav);

        //获取回收站权限
        $show_recycle = $this->checkRule('Admin/article/recycle');
        $this->assign('show_recycle', IS_ROOT || $show_recycle);
        //获取草稿箱权限
        $this->assign('show_draftbox', C('OPEN_DRAFTBOX'));
    }

    /**
     * 分类文档列表页
     * @param $cate_id 分类id
     * @author 朱亚杰 <xcoolcc@gmail.com>
     */
    public function index($cate_id = null){
        //获取左边菜单
        $this->getMenu();

        if($cate_id===null){
            $cate_id = $this->cate_id;
        }

        //获取模型信息
        $model = M('Model')->getByName('document');

        //解析列表规则
        $fields = array();
        $grids  = preg_split('/[;\r\n]+/s', $model['list_grid']);
        foreach ($grids as &$value) {
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }

        // 过滤重复字段信息 TODO: 传入到查询方法
        $fields = array_unique($fields);

        //获取对应分类下的模型
        if(!empty($cate_id)){   //没有权限则不查询数据
            //获取分类绑定的模型
            $models         =   get_category($cate_id, 'model');
            $allow_reply    =   get_category($cate_id, 'reply');//分类文档允许回复
            $pid            =   I('pid');
            if ( $pid==0 ) {
                //开发者可根据分类绑定的模型,按需定制分类文档列表
                $template = $this->indexOfArticle( $cate_id ); //转入默认文档列表方法
                $this->assign('model',  explode(',',$models));
            }else{
                //开发者可根据父文档的模型类型,按需定制子文档列表
                $doc_model = M('Document')->where(array('id'=>$pid))->find();

                switch($doc_model['model_id']){
                    default:
                        if($doc_model['type']==2 && $allow_reply){
                            $this->assign('model',  array(2));
                            $template = $this->indexOfReply( $cate_id ); //转入子文档列表方法
                        }else{
                            $this->assign('model',  explode(',',$models));
                            $template = $this->indexOfArticle( $cate_id ); //转入默认文档列表方法
                        }
                }
            }

            $this->assign('list_grids', $grids);
            $this->assign('model_list', $model);
            // 记录当前列表页的cookie
            Cookie('__forward__',$_SERVER['REQUEST_URI']);
            $this->display($template);
        }else{
            $this->error('非法的文档分类');
        }
    }

    /**
     * 默认文档回复列表方法
     * @param $cate_id 分类id
     * @author huajie <banhuajie@163.com>
     */
    protected function indexOfReply($cate_id) {
        /* 查询条件初始化 */
        $map = array();
        if(isset($_GET['content'])){
            $map['content']  = array('like', '%'.(string)I('content').'%');
        }
        if(isset($_GET['status'])){
            $map['status'] = I('status');
            $status = $map['status'];
        }else{
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }
        if ( !isset($_GET['pid']) ) {
            $map['pid']    = 0;
        }
        if ( isset($_GET['time-start']) ) {
            $map['update_time'][] = array('egt',strtotime(I('time-start')));
        }
        if ( isset($_GET['time-end']) ) {
            $map['update_time'][] = array('elt',24*60*60 + strtotime(I('time-end')));
        }
        if ( isset($_GET['username']) ) {
            $map['uid'] = M('UcenterMember')->where(array('username'=>I('username')))->getField('id');
        }

        // 构建列表数据
        $Document = M('Document');
        $map['category_id'] =   $cate_id;
        $map['pid']         =   I('pid',0);
        if($map['pid']){ // 子文档列表忽略分类
            unset($map['category_id']);
        }

        $prefix   = C('DB_PREFIX');
        $l_table  = $prefix.('document');
        $r_table  = $prefix.('document_article');
        $list     = M() ->table( $l_table.' l' )
                       ->where( $map )
                       ->order( 'l.id DESC')
                       ->join ( $r_table.' r ON l.id=r.id' );
        $_REQUEST = array();
        $list = $this->lists($list,null,null,null,'l.id id,l.pid pid,l.category_id,l.title title,l.update_time update_time,l.uid uid,l.status status,r.content content' );
        int_to_string($list);

        if($map['pid']){
            // 获取上级文档
            $article    =   $Document->field('id,title,type')->find($map['pid']);
            $this->assign('article',$article);
        }
        //检查该分类是否允许发布内容
        $allow_publish  =   get_category($cate_id, 'allow_publish');

        $this->assign('status', $status);
        $this->assign('list',   $list);
        $this->assign('allow',  $allow_publish);
        $this->assign('pid',    $map['pid']);
        $this->meta_title = '子文档列表';
        return 'reply';//默认回复列表模板
    }
    /**
     * 默认文档列表方法
     * @param $cate_id 分类id
     * @author huajie <banhuajie@163.com>
     */
    protected function indexOfArticle($cate_id){
        /* 查询条件初始化 */
        $map = array();
        if(isset($_GET['title'])){
            $map['title']  = array('like', '%'.(string)I('title').'%');
        }
        if(isset($_GET['status'])){
            $map['status'] = I('status');
            $status = $map['status'];
        }else{
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }
        if ( !isset($_GET['pid']) ) {
            $map['pid']    = 0;
        }
        if ( isset($_GET['time-start']) ) {
            $map['update_time'][] = array('egt',strtotime(I('time-start')));
        }
        if ( isset($_GET['time-end']) ) {
            $map['update_time'][] = array('elt',24*60*60 + strtotime(I('time-end')));
        }
        if ( isset($_GET['nickname']) ) {
            $map['uid'] = M('Member')->where(array('nickname'=>I('nickname')))->getField('uid');
        }

        // 构建列表数据
        $Document = M('Document');
        $map['category_id'] =   $cate_id;
        $map['pid']         =   I('pid',0);
        if($map['pid']){ // 子文档列表忽略分类
            unset($map['category_id']);
        }

        $list = $this->lists($Document,$map,'level DESC,id DESC');
        int_to_string($list);
        if($map['pid']){
            // 获取上级文档
            $article    =   $Document->field('id,title,type')->find($map['pid']);
            $this->assign('article',$article);
        }
        //检查该分类是否允许发布内容
        $allow_publish  =   get_category($cate_id, 'allow_publish');

        $this->assign('status', $status);
        $this->assign('list',   $list);
        $this->assign('allow',  $allow_publish);
        $this->assign('pid',    $map['pid']);

        $this->meta_title = '文档列表';
        return 'index';
    }



    /**
     * 文档新增页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function add(){
        //获取左边菜单
        $this->getMenu();

        $cate_id    =   I('get.cate_id',0);
        $model_id   =   I('get.model_id',0);

        empty($cate_id) && $this->error('参数不能为空！');
        empty($model_id) && $this->error('该分类未绑定模型！');

        //检查该分类是否允许发布
        $allow_publish = D('Document')->checkCategory($cate_id);
        !$allow_publish && $this->error('该分类不允许发布内容！');

        /* 获取要编辑的扩展模型模板 */
        $model      =   get_document_model($model_id);

        //处理结果
        $info['pid']            =   $_GET['pid']?$_GET['pid']:0;
        $info['model_id']       =   $model_id;
        $info['category_id']    =   $cate_id;
        if($info['pid']){
            // 获取上级文档
            $article            =   M('Document')->field('id,title,type')->find($info['pid']);
            $this->assign('article',$article);
        }

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('info',       $info);
        $this->assign('fields',     $fields);
        $this->assign('type_list',  get_type_bycate($cate_id));
        $this->assign('model',      $model);
        $this->meta_title = '新增'.$model['title'];
        $this->display();
    }

    /**
     * 文档编辑页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function edit(){
        //获取左边菜单
        $this->getMenu();

        $id     =   I('get.id','');
        if(empty($id)){
            $this->error('参数不能为空！');
        }

        /*获取一条记录的详细数据*/
        $Document = D('Document');
        $data = $Document->detail($id);
        if(!$data){
            $this->error($Document->getError());
        }

        if($data['pid']){
            // 获取上级文档
            $article        =   M('Document')->field('id,title,type')->find($data['pid']);
            $this->assign('article',$article);
        }
        $this->assign('data', $data);
        $this->assign('model_id', $data['model_id']);

        /* 获取要编辑的扩展模型模板 */
        $model      =   get_document_model($data['model_id']);
        $this->assign('model',      $model);

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('fields',     $fields);


        //获取当前分类的文档类型
        $this->assign('type_list', get_type_bycate($data['category_id']));

        $this->meta_title   =   '编辑文档';
        $this->display();
    }


    /*
    * 文章分类列表
    */
    public function categorylist(){

        if(IS_POST){

        }else{
//            $limit = LIMIT;
//            $count = M('article_type')->count();
//            $Page = new  \Think\Page($count, $limit);// 实例化分页类 传入总记录数
//
//            $Page->setConfig('prev', '上一页');
//            $Page->setConfig('next', '下一页');
//            $Page->setConfig('last', '末页');
//            $Page->setConfig('first', '首页');
//            $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
//            $show = $Page->show();// 分页显示输出
//            $this->assign('page',$show);// 赋值分页输出
//            $typeList = M('article_type')->limit($Page->firstRow.','.$Page->listRows)->order("id desc")->select();
            $typeList = M('article_type')->select();
            $res =list_to_tree($typeList);//处理成分级的嵌套数组
            //处理成一维数组
            $lists = tree_to_array($res);

            $this->assign('lists',$lists);
            $this->display();
        }
    }

    /*
	 * 获取文章分类信息
	 */
    public function getArticleType(){
        if(IS_POST){
            $data = M('article_type')->where(array('id'=>I('post.id')))->find();
            $this->success($data);
        }else{
            $this->error('非法操作');
        }
    }

    /*
     * 删除文章分类信息
     */
    public function delArticleType(){
        if(IS_POST){
            //判断删除的分类是否为父级分类
            $result = M('article_type')->where(array('pid'=>I('post.id')))->find();
            if($result){
                $this->error('不能删除父级分类');
            }else{
                $res = M('article_type')->where(array('id'=>I('post.id')))->delete();
                if($res){
                    $this->success('删除成功');
                }else{
                    $this->error('删除失败');
                }
            }
        }else{
            $this->error('非法操作');
        }
    }

    /*
     * 修改文章分类状态
     */
    public function updateTypeStatus(){

        //2、不允许直接更改父级
        if(IS_POST){
            $data["status"] = intval($_POST["status"]);
            $map["id"] = intval($_POST["id"]);
            //判断更改状态的分类是否为父级分类
            $result = M('article_type')->where(array('pid'=>$map["id"]))->find();

            if($result){
                $this->error('不能更改父级分类状态');
            }else{
                $result = M('article_type')->where($map)->save($data);
                if(is_numeric($result)){
                    $this->success("执行成功");
                }else{
                    $this->error("执行失败");
                }
            }
        }else{
            $this->error('非法操作');
        }
        //3、更改父级同时改变子级的处理(这里页面也要改变子级的状态显示，比较麻烦)
        if(IS_POST){
            $data["status"] = intval($_POST["status"]);
            $map["id"] = intval($_POST["id"]);
            $list = M('article_type')->select();
            $tree = list_to_tree($list,'id','pid','_child',$map['id']);
            $ids = array();
            $ids[] = $map['id'];
            //这里文章分类确定只有2级结构
            if($tree){
                //将子分类的状态也都修改
                foreach($tree as $k){
                    $ids[] = $k['id'];
                }
            }
            $where['id'] = array('in',$ids);
            $result = M('article_type')->where($where)->save($data);
            if(is_numeric($result)){
                $this->success("执行成功");
            }else{
                $this->error("执行失败");
            }
        }else{
            $this->error('非法操作');
        }
        //1、允许直接更改父级状态
        if(IS_POST){
            $data["status"] = intval($_POST["status"]);
            $map["id"] = intval($_POST["id"]);

            $result = M('article_type')->where($map)->save($data);
            if(is_numeric($result)){
                $this->success("执行成功");
            }else{
                $this->error("执行失败");
            }
        }else{
            $this->error('非法操作');
        }
    }

    /*
     * 添加文章分类
     */
    public function typeAdd(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            $post = I('post.');

            //处理参数
            $data['name'] = trim(I('post.name'));
            if($data['name'] == ''){
                $this->error('分类名称不能为空');
            }
            $data['sort'] = trim(I('post.sort'));
            $data['status'] = $post['status'];
            $data['pid'] = $post['pid'];

            //验证通过了
            $res = M('article_type')->add($data);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }else{
            $pids = M('article_type')->where(array('pid'=>0,'status'=>1))->select();
            $this->assign('pids',$pids);
            $this->display();
        }
    }
    /*
     * 修改文章分类
     */
    public function typeEdit(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            //处理参数
            $data['name'] = trim(I('post.name'));
            if($data['name'] == ''){
                $this->error('分类名称不能为空');
            }
            $data['sort'] = trim(I('post.sort'));
            $data['status'] = I('post.status');
            $data['pid'] = I('post.pid');
            $res = M('article_type')->where(array('id'=>I('post.id')))->save($data);
            if(is_numeric($res)){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }else{
            $id = I('get.id');
            if($id){
                $data = M('article_type')->where(array('id'=>I('get.id')))->find();
                $this->assign('data',$data);
                //如果该分类不是顶级分类则显示可选择的父级分类
                if($data['pid'] != 0){
                    $typeList = M('article_type')->where(array('pid'=>0,'status'=>1,'id'=>array('neq',$id)))->select();
                    $res =list_to_tree($typeList);//处理成分级的嵌套数组
                    //处理成一维数组
                    $pids = tree_to_array($res);
                    $this->assign('pids',$pids);
                }
                $this->display();
            }
        }
    }
    /*
     * 文章列表
     */
    public function articleList(){
        $limit = LIMIT;
        $get = I('post.');

        $search_data = array();
        $where = array();
        $searchdata_article = session('searchdata_articlelist');

        if(IS_POST){
            session('searchdata_articlelist',$get);
        }else{
            if(I('get.p')){
                $this->assign('p',I('get.p'));
            }else{
                session('searchdata_articlelist',null);
            }
            $get = $search_data = session('searchdata_articlelist');
        }
        if(isset($get['cid']) && $get['cid'] != ''){
            $search_data['cid'] = $get['cid'];
            if($get['cid'] != 'all' ){
                $tree_list = M('article_type')->field("id,name,pid")->order("sort asc")->select();
                $trees = list_to_tree($tree_list,"id","pid","_child",$get['cid']);

                $getids[] = $get['cid'];
                foreach($trees as $v){
                    $getids[] = $v["id"];
                }
                $where['cid'] = array('in',$getids);
            }
        }

        if(isset($get['searchtype']) && $get['searchtype'] != ''){
            $search_data['searchtype'] = $get['searchtype'];
            if($get['searchtype'] != 'all' ){
                $where['type'] = array('eq',$get['searchtype']);
            }
        }
        if(isset($get['searchname']) && $get['searchname'] != ''){
            $search_data['searchname'] = $get['searchname'];
            $nickname = $get['searchname'];
            $admin_uid = M('member')->where(array('nickname'=>$nickname))->getField('uid');
            $where['admin_uid'] = array('eq',$admin_uid);
        }

        if(isset($get['start_time']) && $get['start_time']){
            $search_data['start_time'] = $get['start_time'];
            $where['addtime'][] = array('gt',strtotime(str_replace('_', ' ', $get['start_time'])));
        }
        if(isset($get['end_time']) && $get['end_time']){
            $search_data['end_time'] = $get['end_time'];
            $where['addtime'][] = array('lt',strtotime(str_replace('_', ' ', $get['end_time'])));
        }


        $count = M('article')->where($where)->count();
        $Page = new  \Think\Page($count, $limit);// 实例化分页类 传入总记录数

        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('last', '末页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
		$pre = C('DB_PREFIX');
        $lists = M('article')->alias('a')->field('a.*,b.nickname,c.name')
            ->join($pre.'member b on a.admin_uid = b.uid ','left')
            ->join($pre.'article_type c on a.cid = c.id','left')
            ->where($where)
            ->limit($Page->firstRow.','.$Page->listRows)->order("addtime desc")->select();
//        dump(M('article')->getLastSql());
        $this->assign('searchs',$search_data);
        $this->assign('lists',$lists);
        $typeList = M('article_type')->where(array('status'=>1))->select();
        $res =list_to_tree($typeList);//处理成分级的嵌套数组
        //处理成一维数组
        $types = tree_to_array($res);
        $this->assign('types',$types);
        $this->display();
    }
    /*
     * 添加文章
     */
    public function articleAdd(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            if($_FILES){
                $path = "/Uploads/Article/ShareImg/" . date("Y-m-d") . "/";
                $res = $this->upload_img($_FILES,$path);
                if($res){
                    $data['s_img_url'] = $res;
                }
            }

            $post = I('post.');
            $data['admin_uid'] = $post['admin_uid'];
            $data['type'] = $post['type'];
            $data['cid'] = $post['cid'];
            $data['title'] = trim($post['title']);
            $data['stitle'] = trim($post['stitle']);
            $data['sdest'] = $post['sdest'];
//            $data['s_img_url'] = $post['s_img_url'];
            $data['intro'] = $post['intro'];
            $data['content'] = htmlspecialchars($post['editorValue']);;
            $data['addtime'] = time();
            $data['attachment'] = I('post.attachment','');
            if($data['type'] == 2){
                if($data['attachment'] == ''){
                    $this->error('视频类型文章必须填写视频链接');
                }
            }
            $res = M('article')->add($data);

            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }else{
            $typeList = M('article_type')->where(array('status'=>1))->select();
            $res =list_to_tree($typeList);//处理成分级的嵌套数组
            //处理成一维数组
            $types = tree_to_array($res);
            $this->assign('types',$types);
            $this->display();
        }
    }

    /*
     * 上传
     */
    public function UploadArticle(){}

    /*
     * 删除文章
     */
    public function articleDel(){
        if(IS_POST){
            //先删除对应的评论
            $res = M('comment')->where(array('tid'=>I('post.id')))->delete();

            if(is_numeric($res)){
                //删除图片
                $cover_pic = M('article')->where(array('id'=>I('post.id')))->getField("s_img_url");
                if($cover_pic){@unlink($_SERVER['DOCUMENT_ROOT'].$cover_pic);}
                $res = M('article')->where(array('id'=>I('post.id')))->delete();
                if($res){
                    $this->success('删除成功');
                }else{
                    $this->error('删除失败');
                }
            }else{
                $this->error('删除失败');
            }
        }else{
            $this->error('非法操作');
        }
    }

    /*
     * 编辑文章
     */
    public function articleEdit(){
        if(I('post.btn')){$this->success('');}
        if(IS_POST){
            $post = I('post.');
            $id = $post['id'];
            if($_FILES) {//修改了图片
                $info = M('article')->where(array('id' => $id))->find();
                //删除原图
                $path = $_SERVER['DOCUMENT_ROOT'] . $info['s_img_url'];
                @unlink($path);
                $path = "/Uploads/Article/ShareImg/" . date("Y-m-d") . "/";
                $res = $this->upload_img($_FILES, $path);
                if ($res) {
                    $data['s_img_url'] = $res;
                }
            }

            $data['admin_uid'] = $post['admin_uid'];
            $data['type'] = $post['type'];
            $data['cid'] = $post['cid'];
            $data['title'] = trim($post['title']);
            $data['stitle'] = trim($post['stitle']);
            $data['sdest'] = $post['sdest'];
            $data['intro'] = $post['intro'];
            $data['content'] = htmlspecialchars($post['editorValue']);
            $data['addtime'] = time();
            $data['attachment'] = I('post.attachment','');
            if($data['type'] == 2){
                if($data['attachment'] == ''){
                    $this->error('视频类型文章必须填写视频链接');
                }
            }

            $res = M('article')->where(array('id'=>$id))->save($data);

            if($res){
                $this->success('编辑成功');
            }else{
                $this->error('编辑失败');
            }
        }else{
            $id = I('get.id');
            if($id){
                $data = M('article')->where(array('id'=>I('get.id')))->find();
                $this->assign('data',$data);
                $typeList = M('article_type')->where(array('status'=>1))->select();
                $res =list_to_tree($typeList);//处理成分级的嵌套数组
                //处理成一维数组
                $types = tree_to_array($res);
                $this->assign('types',$types);
                $this->display();
            }
        }
    }

}
